<template>
  <el-card style="width: 1000px; margin: 0 auto;" v-if="confirmInfo">
    <el-steps :active="1" align-center finish-status="success">
      <el-step title="选择商品"></el-step>
      <el-step title="填写核对订单信息"></el-step>
      <el-step title="成功提交订单"></el-step>
    </el-steps>
    <el-divider>订单商品</el-divider>
    <el-row :gutter="20" style="margin-bottom:10px;">
      <el-col :span="4" class="table-title">缩略图</el-col>
      <el-col :span="12" class="table-title">名称\属性</el-col>
      <el-col :span="4" class="table-title">数量</el-col>
      <el-col v-if="isSuperAdmin" :span="4" class="table-title" style="text-align:right;">单价</el-col>
    </el-row>
    <el-row :gutter="20" style="margin-bottom:10px;">
      <el-col :span="4">
        <div class="square">
          <div class="square-content">
            <el-image class="thumb" :src="confirmInfo.goods.thumb" fit="cover"></el-image>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="goods-name">{{ confirmInfo.goods.name }}</div>
        <div style="margin-top:5px;" v-if="confirmInfo.goods.attributes && confirmInfo.goods.attributes.length > 0">
          <span class="goods-att" v-for="att in confirmInfo.goods.attributes" :key="att.id">{{ att.name }}：{{ att.values[0].name }}</span>
        </div>
      </el-col>
      <el-col :span="4">
        <el-form ref="countForm" :model="count" :inline="true" :rules="{
          count: [{ required: true, message: '请输入商品数量' }, { type: 'number', message: '必须为数字值' }]
        }">
          <el-form-item prop="count">
            <el-input v-model.number="count.count" type="number" min="1" step="1" style="width:100px;"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" v-if="confirmInfo.price">
        <div style="text-align:right;"><span class="price">¥{{ confirmInfo.price.toFixed(2) }}</span></div>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-bottom:20px;" v-if="confirmInfo.goods.goodsType.name === 'Gallery'">
      <el-col :span="4">
        <div class="square">
          <div class="square-content">
            <el-image class="thumb" :src="confirmInfo.goods.thumb" fit="cover"></el-image>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="goods-name">增加相册图片</div>
        <div style="margin-top:5px;" v-if="confirmInfo.goods.maxCount">
          <span class="goods-att">最多增加{{ confirmInfo.goods.maxCount - confirmInfo.goods.photoSpecs[0].number }}张</span>
        </div>
      </el-col>
      <el-col :span="4">
        <el-form ref="addCountForm" :model="count" :inline="true" :rules="{
          addCount: [{ type: 'number', message: '必须为数字值' }]
        }">
          <el-form-item v-if="confirmInfo.goods.goodsType.name === 'Gallery'" prop="addCount">
            <el-input v-model.number="count.addCount" type="number" min="0" step="1" :max="confirmInfo.goods.maxCount ? (confirmInfo.goods.maxCount - confirmInfo.goods.photoSpecs[0].number) : 999999" style="width:100px;"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4" v-if="confirmInfo.overPrice">
        <div style="text-align:right;"><span class="price">¥{{ confirmInfo.overPrice.toFixed(2) }}</span></div>
      </el-col>
    </el-row>
    <div v-if="confirmInfo.price" style="text-align:right;">商品金额：{{ count.count }} × {{ confirmInfo.price.toFixed(2) }} = <span class="price">¥{{ confirmInfo.amount.toFixed(2) }}</span></div>
    <div style="text-align:right;" v-if="confirmInfo.goods.goodsType.name === 'Gallery'">+ 增加图片金额：{{ count.addCount }} × {{ confirmInfo.overPrice.toFixed(2) }} = <span class="price">¥{{ confirmInfo.overAmount.toFixed(2) }}</span></div>
    <div v-if="confirmInfo.totalAmount" style="text-align:right;">合计 = <span class="price">¥{{ confirmInfo.totalAmount.toFixed(2) }}</span></div>
    <el-divider>支付方式</el-divider>
    <payment-view v-if="confirmInfo.accountBalance > 0 || confirmInfo.offLineAccountBalance > 0" ref="paymentVew" :accountBalance="confirmInfo.accountBalance" :offLineAccountBalance="confirmInfo.offLineAccountBalance"
      :payType="'AccountBalance'" :usePayTypes="['AccountBalance', 'FactoryCoin']" businessType="order" @paid-finished="paidFinished($event)" :totalAmount="confirmInfo.totalAmount"></payment-view>
    <div v-else>
      <router-link :to="{ name: '账户充值' }">
        <el-link type="primary">请先充值</el-link>
      </router-link>
    </div>
    <el-divider>联系人信息</el-divider>
    <el-form ref="customerForm" :model="customer" :inline="true" :rules="{
      customer: [{required: true, message: '请输入联系人'}],
      customerTel: [{required: true, message: '请输入联系人电话'}]
    }">
      <el-form-item label="联系人" prop="customer">
        <el-input v-model="customer.customer"></el-input>
      </el-form-item>
      <el-form-item label="联系人电话" prop="customerTel">
        <el-input v-model="customer.customerTel"></el-input>
      </el-form-item>
    </el-form>
    <el-divider>收货人信息</el-divider>
    <el-form :ref="'deliverForm_' + index" :model="deliverInfo" :inline="true" v-for="(deliverInfo, index) in deliverInfos" :key="index" :rules="{
      deliverContact: [{required: true, message: '请输入联系人'}],
      deliverContactMobile: [{required: true, message: '请输入联系人电话'}],
      deliverAddress: [{required: true, message: '请输入收货地址'}]
    }">
      <el-form-item label="联系人" prop="deliverContact">
        <el-input v-model="deliverInfo.deliverContact"></el-input>
      </el-form-item>
      <el-form-item label="联系人电话" prop="deliverContactMobile">
        <el-input v-model="deliverInfo.deliverContactMobile"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="deliverAddress">
        <el-input v-model="deliverInfo.deliverAddress"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" circle @click="removeDeliverInfo(index)"></el-button>
      </el-form-item>
    </el-form>
    <div style="margin-top:10px;">
      <el-button v-if="deliverInfos.length < count.count" type="primary" @click="addDeliverInfo">添加收货人</el-button>
    </div>
    <template v-if="qiniuConfig">
      <el-divider>附加信息上传</el-divider>
      <single-file-uploader ref="deliverExtraUploader" :data="{token: qiniuConfig.token}"
      :domain="qiniuConfig.domain" :action="qiniuConfig.uploadUrl" :filePath.sync="deliverExtraFile" :fileSuffixs="['xls', 'xlsx', 'doc', 'docx', 'word', 'pdf']" accept="application/msword, application/vnd.ms-excel, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
    </template>
    <el-divider></el-divider>
    <div style="text-align:center;">
      <el-button type="danger" @click="buyIt" :disabled="confirmInfo.accountBalance === 0 && confirmInfo.offLineAccountBalance === 0">{{ confirmInfo.accountBalance === 0 && confirmInfo.offLineAccountBalance === 0 ? '请充值' : '提交订单' }}</el-button>
    </div>
  </el-card>
</template>

<script>
import orderApi from '@/api/order'
import qiniuApi from '@/api/qiniu'
import SingleFileUploader from '@/components/uploader/singleFileUploader'
import PaymentView from '@/components/payment/paymentView'
import waves from '@/directive/waves' // 水波纹指令
import { mapGetters } from 'vuex'

export default {
  directives: {
    waves
  },
  components: {
    SingleFileUploader, PaymentView
  },
  computed: {
    ...mapGetters([
      'mainContainerHeight', 'isSuperAdmin'
    ])
  },
  watch: {
    mainContainerHeight: function (newHeight, oldHeight) {
      this.resize()
    },
    'count.count': function (newCount, oldCount) {
      if ((newCount + '').indexOf('.') > -1) {
        this.count.count = Math.ceil(newCount)
      }
      if (newCount <= 0) {
        this.count.count = 1
      }
      if (newCount < this.deliverInfos.length) {
        this.deliverInfos.splice(newCount)
      }
      this.refreshPrice()
    },
    'count.addCount': function (newCount, oldCount) {
      if (newCount === '') {
        this.count.addCount = 0
      }
      if ((newCount + '').indexOf('.') > -1) {
        this.count.addCount = Math.ceil(newCount)
      }
      if (newCount < 0) {
        this.count.addCount = 0
      }
      if (this.confirmInfo.goods.maxCount && this.count.addCount > this.confirmInfo.goods.maxCount - this.confirmInfo.goods.photoSpecs[0].number) {
        this.count.addCount = this.confirmInfo.goods.maxCount - this.confirmInfo.goods.photoSpecs[0].number
      }
      this.refreshPrice()
    }
  },
  data () {
    return {
      id: null,
      attributes: null,
      clientHeight: 500,
      confirmInfo: null,
      selectedAttributes: [],
      customer: {
        customer: '',
        customerTel: ''
      },
      count: {
        count: 1,
        addCount: 0
      },
      deliverExtraFile: null,
      deliverInfos: [
        {
          deliverContact: '',
          deliverContactMobile: '',
          deliverAddress: ''
        }
      ],
      qiniuConfig: null,
      orderId: null
    }
  },
  methods: {
    /**
     * 加载数据
     */
    confirmGoods () {
      orderApi
        .confirmPrice({
          goodsId: this.id * 1,
          attributes: this.attributes ? this.attributes.map(att => att * 1) : null,
          count: 1,
          addCount: 0
        })
        .then((response) => {
          this.confirmInfo = response.data
        })
    },
    /**
     * 获取七牛配置
     */
    getQiniuConfig () {
      qiniuApi.getOtherConfig().then(response => {
        this.qiniuConfig = response.data
      })
    },
    /**
     * 刷新价格
     */
    refreshPrice () {
      if (this.count.count > 0) {
        orderApi
          .confirmPrice({
            goodsId: this.id * 1,
            attributes: this.attributes ? this.attributes.map(att => att * 1) : [],
            count: this.count.count,
            addCount: this.count.addCount
          })
          .then((response) => {
            this.confirmInfo.amount = response.data.amount
            this.confirmInfo.overAmount = response.data.overAmount
            this.confirmInfo.totalAmount = response.data.totalAmount
          })
      }
    },
    /**
     * 移除收货人信息
     *
     * @param index 序号
     */
    removeDeliverInfo (index) {
      this.deliverInfos.splice(index, 1)
    },
    /**
     * 添加收货人信息
     */
    addDeliverInfo () {
      if (this.deliverInfos.length < this.count.count) {
        this.deliverInfos.push({
          deliverContact: '',
          deliverContactMobile: '',
          deliverAddress: ''
        })
      }
    },
    /**
     * 立即下单
     */
    buyIt () {
      var validate = []
      validate.push(new Promise((resolve, reject) => {
        this.$refs.countForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject(new Error())
          }
        })
      }))
      if (this.confirmInfo.goods.goodsType.name === 'Gallery') {
        validate.push(new Promise((resolve, reject) => {
          this.$refs.addCountForm.validate((valid) => {
            if (valid) {
              resolve()
            } else {
              reject(new Error())
            }
          })
        }))
      }
      validate.push(new Promise((resolve, reject) => {
        this.$refs.customerForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            reject(new Error())
          }
        })
      }))
      const that = this
      for (var i = 0; i < this.deliverInfos.length; i++) {
        validate.push(new Promise((resolve, reject) => {
          that.$refs['deliverForm_' + i][0].validate((valid) => {
            if (valid) {
              resolve()
            } else {
              reject(new Error())
            }
          })
        }))
      }
      Promise.all(validate).then(() => {
        orderApi.insert({
          goodsId: this.id,
          count: this.count.count,
          deliverInfos: this.deliverInfos,
          addPhotoCount: this.count.addCount,
          goodsAttributeValues: this.attributes,
          customer: this.customer.customer,
          customerTel: this.customer.customerTel,
          extraFile: this.deliverExtraFile
        }).then((response) => {
          // this.$alert('订单提交成功', '提示', {
          //   confirmButtonText: '确定',
          //   callback: action => {
          //     this.$router.pushTo(this.$router.routesConfig.orderInfo, response.data.id)
          //   }
          // })
          this.orderId = response.data.id
          this.$refs.paymentVew.startPayment(response.data.id)
        })
      })
    },
    /**
     * 支付完成
     *
     * @param {*} event 事件参数
     */
    paidFinished (event) {
      if (event.success) {
        this.$router.pushTo(this.$router.routesConfig.orderInfo, this.orderId)
      } else {
        this.$alert(`未完成支付：${event.message}。`, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.pushTo(this.$router.routesConfig.orderInfo, this.orderId)
          }
        })
      }
    },
    resize () {
      var that = this
      that.clientHeight = that.mainContainerHeight - 80
    }
  },
  mounted () {
    this.id = this.$route.query.id
    this.attributes = this.$route.query.attributes
    this.confirmGoods()
    this.getQiniuConfig()
    var that = this
    this.$nextTick(function () {
      that.resize()
    })
  }
}
</script>
<style lang="scss" scoped>
  .thumb {
    width: 100%;
    height: 100%;
    display: block;
  }

  .goods-name {
    color: #303133;
    font: 700 16px Arial,"microsoft yahei";
  }

  .goods-att {
    color: #606266;
    font: 300 14px Arial,"microsoft yahei";
    margin-right: 10px;
    margin-bottom: 5px;
    float: left;
  }

  .price {
    font-weight: bold;
    font-size: 22px;
    color: #f56c6c;
  }

  .square {
    padding-bottom:100%;
    height: 0;
    width: 100%;
    position: relative;
  }

  .square-content {
    width: 100%;
    height: 100%;
    position: absolute;
    top:0;
    left:0;
  }

  .table-title {
    color: #303133;
    font: 700 12px Arial,"microsoft yahei";
  }
</style>
